import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/app/yhpc/YhpcViewModel.dart';
import 'package:flutter_ahj_app/base/basewidget/view/BaseWidget.dart';
import 'package:flutter_ahj_app/base/utils/EmptyUtils.dart';
import 'package:flutter_ahj_app/base/utils/JUIKit/JText.dart';
import 'package:flutter_ahj_app/base/utils/StringUtils.dart';
import 'package:flutter_ahj_app/base/utils/ToastUtils.dart';
import 'package:flutter_ahj_app/base/utils/mTopBar.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';
import 'package:flutter_ahj_app/base/values/dimens.dart';
import 'package:flutter_ahj_app/base/widget/LoadingWidget.dart';
import 'package:flutter_ahj_app/base/widget/NoneData.dart';

class ChoosePerson extends BaseStatefulWidget {
  final Map chooseMap;
  ChoosePerson({Key key, this.chooseMap});

  @override
  State<StatefulWidget> initState() {
    // TODO: implement initState
    // throw UnimplementedError();
    return ChoosePersonState();
  }
}

class ChoosePersonState extends BaseState<YhpcViewModel, ChoosePerson> {
  TextEditingController _controller = TextEditingController(text: '');
  List _list;
  List _selList = [];

  List _hxSelList = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    
    if (!EmptyUtils.isForEmpty(widget.chooseMap['sel'])) {
      for (var i = 0; i < widget.chooseMap['sel'].length; i++) {
        if (widget.chooseMap['sel'][i] is String) {
          Map map = {
            'openId': widget.chooseMap['sel'][i]
          };
          _hxSelList.add(map);
        }else {
          _hxSelList.add(widget.chooseMap['sel'][i]);
        }
      }
    }
    Future.delayed(Duration.zero, () {
      _getData();
    });
  }

  _getData() {
    var map = {
      'keyWord': _controller.text,
      'orgCodes': EmptyUtils.isForEmpty(widget.chooseMap) ? '' : [widget.chooseMap['selOrgCode']],
      'current': '1',
      'size': '9999',
    };
    viewModel.getPerson(map);
    viewModel.getPersonDataStream().listen((event) {
      if (event['code'] == '0') {
        setState(() {
          _list = [];
          _list = event['data']['records'];
          if(!EmptyUtils.isForEmpty(_list) && !EmptyUtils.isForEmpty(_hxSelList)) {
            List _selmrList = [];
            for(int i=0;i<_list.length;i++){
              for(int j=0;j<_hxSelList.length;j++){
                if(StringUtils.getStr(_list[i]['openId'].toString()) == StringUtils.getStr(_hxSelList[j]['openId'].toString())) {
                  _list[i]['isSel'] = true;
                  _selmrList.add(_list[i]);
                }
              }
            }
            _selList = _selmrList;
          }
        });
      } else {
        ToastUtils.showToast(event['msg']);
      }
    }, onError: (e) {
      print(e);
    });
  }

  @override
  Widget initWidget() {
    return Scaffold(
      backgroundColor: Color(0xfff4f5f6),
      appBar: MTopBar(
              elevation: 0,
              title: '选择排查人',
              rightButtonText: '确定',
              onRightButtonClick: () {
                if(_selList.length == 0) {
                  return ToastUtils.showToast('请选择排查人');
                }
                print(_selList);
                Navigator.pop(context, _selList);
              })
          .create(),
      body: _list == null
          ? LoadingWidget()
          : _bodyView(),
    );
  }

  _getPerson(List list) {
    // 按逗号拼接
    String ids = '';
    for (var i = 0; i < list.length; i++) {
      String string = '';
        if(ids.length>0){
          string = '、';
        }
        ids = ids + string + list[i]['orgName'];
    }
    return ids;
  }

  _bodyView() {
    return Column(
      children: [
        _searchLayout(),
        Expanded(
          child: _list.length == 0
              ? NoneData() : Container(
            color: SQColor.white,
            padding: EdgeInsets.fromLTRB(
                Dimens.dimens16, 0, Dimens.dimens16, Dimens.dimens16),
            child: SingleChildScrollView(
              child: ListView.builder(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  itemCount: _list.length,
                  itemBuilder: (context, index) {
                    return InkWell(
                      onTap: () {
                        setState(() {
                          _list[index]['isSel'] = _list[index]['isSel'] == null
                              ? true
                              : !_list[index]['isSel'];
                          if (_list[index]['isSel']) {
                            _selList.add(_list[index]);
                          } else {
                            _selList.remove(_list[index]);
                          }
                        });
                      },
                      child: Column(
                        children: [
                          Container(
                            child: Row(
                              children: [
                                Expanded(
                                    child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      margin: EdgeInsets.only(top: 10),
                                      child: JText(_list[index]['name'] ?? ''),
                                    ),
                                    Container(
                                      margin:
                                          EdgeInsets.only(top: 10, bottom: 10),
                                      child: JText(_getPerson(_list[index]['organizations'])),
                                    ),
                                  ],
                                )),
                                Checkbox(
                                  value: _list[index]['isSel'] == null
                                      ? false
                                      : _list[index]['isSel'],
                                  onChanged: (value) {
                                    setState(() {
                                      _list[index]['isSel'] = _list[index]['isSel'] == null
                                          ? true
                                          : !_list[index]['isSel'];
                                      if (_list[index]['isSel']) {
                                        _selList.add(_list[index]);
                                      } else {
                                        _selList.remove(_list[index]);
                                      }
                                    });
                                  },
                                ),
                              ],
                            ),
                          ),
                          Container(
                            height: 1,
                            color: Color(0xfff6f6f6),
                            width: double.infinity,
                          ),
                        ],
                      ),
                    );
                  }),
            ),
          ),
        ),
      ],
    );
  }

  _searchLayout() {
    return Container(
      margin: EdgeInsets.all(Dimens.dimens16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(6.0),
      ),
      child: Row(
        children: [
          Container(
            width: 20,
            height: 20,
            margin: EdgeInsets.only(left: 10),
            child: Icon(
              Icons.search,
              color: Color(0xffaaaaaa),
            ),
          ),
          Expanded(
            child: Container(
              height: Dimens.dimens36,
              child: TextField(
                controller: _controller,
                maxLines: 1,
                onSubmitted: (value) {
                  _getData();
                },
                decoration: InputDecoration(
                  hintText: "请输入排查人名称搜索",
                  hintStyle: TextStyle(fontSize: Dimens.textSize28),
                  fillColor: Colors.white,
                  //filled = true 时为背景颜色
                  filled: true,
                  contentPadding: EdgeInsets.fromLTRB(
                      Dimens.dimens16, 0, Dimens.dimens16, 0),
                  enabledBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius:
                        BorderRadius.all(Radius.circular(Dimens.dimens4)), //圆角
                    borderSide: BorderSide(color: Colors.white, width: 1), //边框
                  ),
                  suffixIcon: _controller.text.length > 0
                      ? new IconButton(
                          icon: Icon(
                            Icons.close,
                            color: SQColor.per38Black,
                            size: Dimens.dimens20,
                          ),
                          onPressed: () {
                            setState(() {
                              _controller.clear();
                              _getData();
                            });
                          })
                      : null,
                ),
              ),
            ),
          ),
          Container(
            width: 1,
            color: SQColor.black_BDBDBD,
            height: Dimens.dimens16,
            margin: EdgeInsets.only(right: Dimens.dimens16),
          ),
          GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
              _getData();
            },
            child: Container(
              padding: EdgeInsets.only(right: Dimens.dimens16),
              height: Dimens.dimens48,
              alignment: Alignment.centerRight,
              child: Text("搜索",
                  style: TextStyle(
                      color: Color(0xff165DFF), fontSize: Dimens.textSize28)),
            ),
          ),
        ],
      ),
    );
  }
}
